'use server'
import { auth } from "@/auth";
import { prisma } from "@/prisma";
import { Post } from "@prisma/client";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { z } from "zod";

const schema = z.object({
  title: z.string().min(3, "标题长度不能小于3").max(20, "标题长度不能大于20"),
  content: z.string().min(10, "内容长度不能小于10").max(1000, "内容长度不能大于1000"),
})


interface CreatePostFormState {
  errors: {
    title?: string[];
    content?: string[];
    _form?: string[];
  };
}

/**
 * 
 * @param name 话题名称
 * @param formData 表单数据
 * @returns 
 */
export async function createPost(name: string, formState: CreatePostFormState, formData: FormData): Promise<CreatePostFormState> {
  // 先试用 zod 模块对入参进行校验
  const title = formData.get("title") as string;
  const content = formData.get("content") as string;
  const result = schema.safeParse({
    title,
    content
  })
  if (!result.success) {
    return {
      errors: result.error.flatten().fieldErrors,
    }
  }
  //通过auth模块 判断用户是否登录
  const session = await auth();
  if (!session?.user) {
    return {
      errors: {
        _form: ["请先登录"],
      }
    }
  }
  // 根据话题名字找出对应的话题信息
  const topic = await prisma.topic.findFirst({
    where: {
      name
    }
  })
  if (!topic) {
    return {
      errors: {
        _form: ["话题不存在"],
      }
    }
  }
  // 创建帖子
  let post: Post
  try {
    post = await prisma.post.create({
      data: {
        title: result.data.title,
        content: result.data.content,
        userId: session.user.id,
        topicId: topic.id,
      }
    })
  } catch (error) {
    if (error instanceof Error) {
      return {
        errors: {
          _form: [error.message],
        }
      }
    } else {
      return {
        errors: {
          _form: ["创建失败"],
        }
      }
    }
  }
  revalidatePath('/');
  redirect(`/topics/${name}/posts/${post.id}`);
}
